#include "at32f403a_407_board.h"
#include "at32f403a_407_clock.h"
#include <at32f403a_407_usb.h>
//#include <usbd_core.h>

static void init_gpio(gpio_type *gpio_baseABCD,uint32_t pins,gpio_mode_type typ){
  gpio_init_type gpio_init_struct;

  /* enable the led clock */
  crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);
  crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE);
  crm_periph_clock_enable(CRM_GPIOC_PERIPH_CLOCK, TRUE);

  /* set default parameter */
  gpio_default_para_init(&gpio_init_struct);

  /* configure the led gpio */
  gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_MODERATE;
  gpio_init_struct.gpio_out_type  = GPIO_OUTPUT_PUSH_PULL;
  gpio_init_struct.gpio_mode = typ;
  gpio_init_struct.gpio_pins = pins;
  gpio_init_struct.gpio_pull = GPIO_PULL_NONE;
  gpio_init(gpio_baseABCD, &gpio_init_struct);
}

int SystemCoreClock = 192000000;

static int getrx_buf(uint8_t *buf,int len,int _break_c){
	int pos = 0;
	//usart_flag_clear(USART1, USART_RDBF_FLAG);
	while(pos<len){
		while(usart_flag_get(USART1, USART_RDBF_FLAG) == RESET);
		u16 dat = usart_data_receive(USART1);
		usart_flag_clear(USART1, USART_RDBF_FLAG);
		if(_break_c==dat){
			break;
		}
		buf[pos++] = dat;
	}
	return pos;
}

void usb_clock48m_select(usb_clk48_s clk_s)
{
  if(clk_s == USB_CLK_HICK)
  {
    crm_usb_clock_source_select(CRM_USB_CLOCK_SOURCE_HICK);

    /* enable the acc calibration ready interrupt */
    crm_periph_clock_enable(CRM_ACC_PERIPH_CLOCK, TRUE);

    /* update the c1\c2\c3 value */
    acc_write_c1(7980);
    acc_write_c2(8000);
    acc_write_c3(8020);

    /* open acc calibration */
    acc_calibration_mode_enable(ACC_CAL_HICKTRIM, TRUE);
  }
  else
  {
    switch(system_core_clock)
    {
      /* 48MHz */
      case 48000000:
        crm_usb_clock_div_set(CRM_USB_DIV_1);
        break;

      /* 72MHz */
      case 72000000:
        crm_usb_clock_div_set(CRM_USB_DIV_1_5);
        break;

      /* 96MHz */
      case 96000000:
        crm_usb_clock_div_set(CRM_USB_DIV_2);
        break;

      /* 120MHz */
      case 120000000:
        crm_usb_clock_div_set(CRM_USB_DIV_2_5);
        break;

      /* 144MHz */
      case 144000000:
        crm_usb_clock_div_set(CRM_USB_DIV_3);
        break;

      /* 168MHz */
      case 168000000:
        crm_usb_clock_div_set(CRM_USB_DIV_3_5);
        break;

      /* 192MHz */
      case 192000000:
        crm_usb_clock_div_set(CRM_USB_DIV_4);
        break;

      default:
        break;

    }
  }
}

//usbd_core_type udevd;
//usbd_core_type *udev = &udevd;
//extern usbd_desc_handler  jtag_desc_handler;
//extern usbd_class_handler jtag_class_handler;

int init_usb(){
	int core_id = 0;
	nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
	usb_clock48m_select(USB_CLK_HEXT);
	crm_periph_clock_enable(CRM_USB_PERIPH_CLOCK, TRUE);
	//nvic_irq_enable(USBFS_L_CAN1_RX0_IRQn,0,0);

  hid_main();
}

int dap_link_loop(){
	//初始化usb
	init_usb();
	while(1){};
	return 0;
}

